const {RedisClient} = require("./redisClient");
const {setCookieFromResponseHeaders} = require("./cookieTools");
const {processAkamaiPyFile} = require("./process");
const crypto = require("crypto");
const http = require("./superagentHttp");
const axios = require('axios');
const log = require('./log');


function md5(text) {
    return crypto.createHash('md5').update(text).digest('hex');
}

async function getValue(url) {
    const key = md5(url);
    const redisConn = await new RedisClient().getConn();
    let value;
    try {
        // await redisConn.del(key);
        value = await redisConn.get(key);
    } catch (err) {
    } finally {
        redisConn.disconnect();
    }
    return value
}

async function setValue(url, value, ex = 60 * 30) {
    if (value.trim() === ''){
        return;
    }
    const key = md5(url);
    const redisConn = await new RedisClient().getConn();
    await redisConn.set(key, value, 'EX', ex)
    redisConn.disconnect();
}

function parseSetCookieHeader(setCookieHeader) {
    const cookiesArray = setCookieHeader.split(', ');

    const keyValuePairs = cookiesArray.map(cookie => {
        const [keyValue, ...options] = cookie.split('; ');
        const [key, value] = keyValue.split('=');

        return {key, value};
    });

    return keyValuePairs.map(pair => `${pair.key}=${pair.value}`).join('; ');
}


async function getCacheElseRequest(url, headers, timeout, traceId, productName, retryCount, blackUrl = null,
                                   needProxy = true, proxy_config = null, axio = false, ex = 900,
                                   callback = null, py = false, method = 'get', cookies = null, data = null, saveCache = true) {
    async function getCacheElseRequestPyCallback(response, referer) {
        let respText = response['text'];
        const newCookie = response['headers']['set-cookie'];
        if (newCookie) {
            setCookieFromResponseHeaders(newCookie, referer);
        }

        if (saveCache && respText && respText.indexOf('Access Denied') === -1) {
            await setValue(url, respText, ex);
        }
        await callback(respText);
    }

    let value = '';
    if (blackUrl && url.indexOf(blackUrl) !== -1) {
        value = false;
    } else {
        value = await getValue(url);
    }
    if (!value) {
        if (py && callback) {
            await processAkamaiPyFile(url, method, cookies, data, headers, log, traceId, productName, getCacheElseRequestPyCallback);
            return
        }
        if (axio) {
            const axios_config = {
                method: "get", url: url,
                headers: headers,
                timeout: timeout,
            }
            if (needProxy) {
                axios_config['auth'] = {
                    username: 'jsengine',
                    password: 'jsengine123456'
                };
                axios_config['proxy'] = {
                    protocol: 'http',
                    host: 'iproxy.fly.17usoft.com',
                    port: 8080,

                    auth: {
                        username: 'jsengine',
                        password: 'jsengine123456'
                    }
                };
            }
            value = await axios(axios_config);
            value = value.data;
        } else {
            value = await http.request(method.toUpperCase(), url, headers, data, retryCount, timeout, false, false, needProxy,
                proxy_config, false);
        }
        if (saveCache && value && value.indexOf('Access Denied') === -1) {
            await setValue(url, value, ex);
        }
    } else {
        log.info(`[${productName}][%s] %s 响应已从redis缓存获取`, traceId, url);
    }
    if (value && callback) {
        await callback(value);
    }
    return value
}

// !(async ()=>{
//     let value = '';
//     value = await getCacheElseRequest('https://www.chinaexpressair.com/yss/login/');
//     console.log(value);
//
// })()

module.exports = {
    getValue: getValue,
    setValue: setValue,
    getCacheElseRequest: getCacheElseRequest,
    md5: md5
}
